import {RouteRecordRaw} from 'vue-router'

import {useAclStore} from '@/libs/store'
import router from '@/libs/router'
import {SysConfig} from '@/libs/config'
import {ERROR_ROUTER, LAYOUT, NOT_FOUND_ROOTER, ROOT_ROUTER} from '@/libs/router/constant'
import {EmptyUtil, TreeUtil} from "@/utils";
import {AccountApi} from "@/libs/api";


export class RouterUtil {
    // 根据当前路径计算登录地址
    static toLoginRoute(currentPath) {
        if (currentPath !== '/')
            return {
                path: '/login',
                query: {redirect: currentPath},
                replace: true,
            }
        return {path: '/login', replace: true}
    }


    // 根据当前路径计算登录地址
    static toLink = (path,query) => router.push({path,query})


    // 设置路由
    static async setupRouter() {

        // 获取PAGE文件夹内所有的VUE组件
        const modules = import.meta.glob('@/pages/modules/**/*.vue')
        if (EmptyUtil.isNotEmptyObject(modules)) {
            const useAclStore1 = useAclStore();
            let menData;
            if (SysConfig.routerSource === 'SERVER') {
                // 查询账号权限对象
                const {data} = await AccountApi.getAclMeta();
                const permission = data.apiExprList
                menData = TreeUtil.listToTree(data.menuList, "0", 'id', 'parentId')
                await useAclStore1.setFullExpr(permission)
                await useAclStore1.setFullRole([])
                await useAclStore1.setFullMenu(menData)
            } else {

                // 本地文件模式构建路由
                const LocaleMenu = import.meta.globEager('@/pages/**/resource/router.ts')
                const keys = Object.keys(LocaleMenu)
                const dataList = [];
                for (let i = 0; i < keys.length; i++) {
                    // @ts-ignore
                    dataList.push(...LocaleMenu[keys[i]].default)
                }

                menData = TreeUtil.listToTree(dataList, 0, 'id', 'parentId')

                await useAclStore1.setFullMenu(menData)


                // 设置人员权限表达式
                const {data} = await AccountApi.getAclMeta();
                await useAclStore1.setFullExpr(data)
                await useAclStore1.setFullExpr([])

            }
            await this.addDynamicRouter(modules, menData, ROOT_ROUTER.name)
            // 安装错误路由
            router.addRoute(ERROR_ROUTER)
            // 安装404
            router.addRoute(NOT_FOUND_ROOTER)

            useAclStore1.setInitRouter(true)

        }


    }


    /**
     * 安装动态路由
     * */
    private static addDynamicRouter(modules: any, list: Record<string, any>[], parentName) {
        // 安装所有路由
        list.forEach(item => {
            const {meta, name, path, children,} = item
            // 判断路由名称是否存在 如果存在 直接跳过
            if (router.hasRoute(name)) return
            const raw = {meta, path, redirect: undefined, name, component: undefined} as RouteRecordRaw
            if (parentName && children && children.length) {
                this.addDynamicRouter(modules, children, parentName)
                raw.redirect = children[0].path
                router.addRoute(parentName, raw)
            } else {
                raw.component = this.getComponentPromise(modules, item.component)
                router.addRoute(parentName, raw)
            }
        })
    }

    // 根据组件字符串获取组件信息
    private static getComponentPromise(modules, component: string) {
        if (component.toLocaleUpperCase() === 'LAYOUT') return LAYOUT
        const root = '/src'
        const keys = Object.keys(modules)
        const findStr = component
        const lastName = findStr.endsWith('.vue') ? findStr : `${findStr}/index.vue`

        const matchKeys = keys.filter(key => {
            const val = key.replace(root, '')
            return val.endsWith(`${lastName}`)
        })
        // 最后找到的 modules 关联的key
        const lastKey = matchKeys[0]
        if (matchKeys?.length === 1) return modules[lastKey]
        return LAYOUT
    }


}
